import React, {FC, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from "react";
import CodeMirror from '@uiw/react-codemirror';

interface GlobalCodeEditProps {
    value: string,
    onChange: Function
}

const GlobalCodeEdit: FC<GlobalCodeEditProps> = (props) => {
    const codeMirrorRef = useRef();
    const [value, setValue] = useState<string>("");

    useEffect(() => {
        setValue(props.value)
    }, [props.value]);

    const getValue: Function = useCallback(() => {
        return codeMirrorRef.current.view.contentDOM.outerText;
    }, []);

    const handleChange: Function = useCallback((value: string) => {
        // console.log(value, "xxxxxxxxxxxx", codeMirrorRef.current.view.contentDOM.outerText)
        // setValue(value);
        // props.onChange && props.onChange(value);
    }, [props.onChange]);

    useImperativeHandle(props.init, () => {
        return {
            getValue,
            codeMirror: () => {
                return codeMirrorRef.current;
            }
        }
    })

    const renderGlobalCodeEdit = useMemo(() => {
        return (
            <CodeMirror
                ref={codeMirrorRef}
                value={value}
                editable={true}
                onChange={handleChange}
            />
        )
    }, [value]);

    return (renderGlobalCodeEdit);
}

export default React.memo(GlobalCodeEdit);